import router from "@/router/index.js";
import {useLoginStore} from "@/pinia/loginStore.js";

router.beforeEach((to, from, next) => {
    console.log(to.path)
    if (to?.meta?.isPublic) {
        console.log('白名单路由')
        next();
    } else {
        // 判断是否登录
        if (localStorage.getItem('blog-token')) {
            console.log('已登录')
            // 获取用户信息
            const loginStore = useLoginStore();
            loginStore.fetchUserInfo().then((data) => {
                console.log('用户信息：', data);
                loginStore.setUserInfo(data);
                if (to.path === '/login') {
                    next({
                        path: '/admin'
                    });
                } else {
                    next();
                }
            }).catch(err => {
                console.log(err);
                localStorage.clear();
                next({
                    path: '/login'
                });
            });
        } else if (to.path === '/login') {
            // 已经登录则直接进入
            next();
        } else {
            console.log('未登录')
            localStorage.clear();
            next({
                path: '/login'
            });
        }
    }
});

